package com.cykj.eurekaribbon.service.Impl;

import com.cykj.eurekaribbon.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Service
public class HelloServiceImpl implements HelloService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Override
    public void get(String id) {
        //访问路径
        String url = "http://CLIENT-TEST/hello";
        //访问所需要携带的参数集合
        Map<String,String> map = new HashMap<>();
        map.put("id",id);
        restTemplate.getForEntity(url,String.class,map);
    }

    @Override
    public void post(String id) {

    }

    @Override
    public String hiService(String name) {
        ServiceInstance instance = loadBalancerClient.choose("CLIENT-TEST");
        URI uri = URI.create(String.format("http://%s:%s/hello?name=" + name,instance.getHost(),instance.getPort()));
//        return restTemplate.getForObject("http://CLIENT-TEST/hello?name="+name,String.class);

        RestTemplate restTemplate = new RestTemplate();
        String msg = restTemplate.getForObject(uri,String.class);
        return msg;
    }
}
